/*
  - @FilePath: /tads/server/app/business/apis/auth.go

* @Author: wnina0x0
* @Date: 2025-04-17 15:40:25
* @Description:
*

* 版权信息 : 2025 by wnina0x0, All Rights Reserved.
*/
package apis

import (
	"crypto/rand"
	"fmt"
	"net/http"
	"tads/server/app/business/service/dto"
	"tads/server/core/sdk/api"
	"tads/server/global"
	"time"

	"github.com/gin-gonic/gin"
	"github.com/gin-gonic/gin/binding"
	"github.com/golang-jwt/jwt/v5"
)

const TokenExpiry = 10 * time.Minute

type Auth struct {
	api.Api
}

type Claims struct {
	User string `json:"user"`
	Role string `json:"role"`
	jwt.RegisteredClaims
}

func (a Auth) InitKey() {
	jwtKey := make([]byte, 32)
	if _, err := rand.Read(jwtKey); err != nil {
		a.Logger.Errorf("token key crete: %s\n", err.Error())
	}
	global.TADS_AUTH_KEY = &jwtKey
}

func (a Auth) Login(c *gin.Context) {
	a.InitKey()
	expirationTime := time.Now().Add(TokenExpiry)
	claims := &Claims{
		User: "admin",
		Role: "admin",
		RegisteredClaims: jwt.RegisteredClaims{
			ExpiresAt: jwt.NewNumericDate(expirationTime),
		},
	}
	token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
	jwtStr, err := token.SignedString(global.TADS_AUTH_KEY)
	if err != nil {
		a.Logger.Errorf("JWT生成错误: %s\n", err.Error())
		return
	}
	c.SetCookie(
		"Token",
		jwtStr,
		10,
		"/",
		"", //是否仅HTTPS
		false,
		true,
	)
}

func (a Auth) CheckOssToken() {}

func (a Auth) ReceiveToken(c *gin.Context) {
	q := dto.AuthOssRequests{}
	err := a.MakeContext(c).Bind(&q, binding.Query).Errors
	if err != nil {
		a.Logger.Errorf("请求参数错误: %s!\n", err.Error())
		c.JSON(http.StatusOK, gin.H{"code": 400, "msg": fmt.Sprintf("请求参数错误: %s!\n", err.Error())})
		return
	}
	c.SetCookie(
		"session",
		q.OssToken,
		3600, // 过期时间（单位为秒）
		"/",
		"", //是否仅HTTPS
		false,
		true,
	)
	c.JSON(http.StatusOK, gin.H{
		"code": 400,
		"msg":  q.OssToken,
	})
}

func (a Auth) Logout(c *gin.Context) {
	c.SetCookie("session", "", -1, "/", "", false, true)
	c.JSON(http.StatusOK, gin.H{
		"code": 400,
		"msg":  "111",
	})
}
